import { FloatButton, Avatar, Space, Tag, Modal, Image } from "antd";
import { MenuOutlined } from "@ant-design/icons";
import { useModel, history, Outlet, useLocation } from "umi";
import { useEffect } from "react";
import { useReactive } from "ahooks";
import { Layout, Nav } from "@douyinfe/semi-ui";
import Jdenticon from "react-jdenticon";

import GlobalHeader from "./components/MainHeader";

const { Header, Content } = Layout;

const MainLayout = () => {
    const { kuboUrl } = useModel("kubo");
    const { loginInfo } = useModel("person.info");
    const { routers, setBreadcrumbs, addBreadcrumb } = useModel("routers");
    const { applicationInfo, applicationName, isStop, isExpire } = useModel("application.info");
    const { remoteOrganizationInfo } = useModel("organization.info");
    const location = useLocation();

    if (!loginInfo.authCenterUrl) {
        Modal.confirm({ content: "没有登录，不能访问组织应用", onOk: () => currentWindow.close(), onCancel: () => currentWindow.close() });
        return <GlobalHeader />;
    }

    const state = useReactive({
        selectedMenuKeys: [],
    });

    useEffect(() => {
        if (location.pathname === "/") {
            setBreadcrumbs([{ title: "首页" }]);
        } else {
            setBreadcrumbs([]);
            const pathname = location.pathname.substr(1);
            let paths = pathname.split("/");
            if (paths.length >= 2) {
                state.selectedMenuKeys = routers[paths[0]]?.isShowSub ? [paths[0] + "/" + paths[1]] : [paths[0]];
                addBreadcrumb({ title: routers[paths[0]].title });
                addBreadcrumb({ title: routers[paths[0]].subMenus[paths[1]].title });
            } else {
                state.selectedMenuKeys = [paths[0]];
                addBreadcrumb({ title: routers[paths[0]].title });
            }
        }
    }, [location.pathname]);

    const onSelectedMenu = ({ itemKey, selectedKeys }) => {
        // TODO: 要判断组织和应用的授权状态是否可用
        state.selectedMenuKeys = selectedKeys;
        if (routers[itemKey].subMenus) itemKey += "/" + Object.keys(routers[itemKey].subMenus)[0];
        history.replace({ pathname: "/" + itemKey });
    };

    const appIcon =
        kuboUrl && applicationInfo?.atIcon ? (
            <Image width={20} src={kuboUrl + applicationInfo.atIcon} preview={false} style={{ padding: "7px 0 " }} />
        ) : (
            <div style={{ padding: "2px 0 " }}>
                <Jdenticon size="30" value={applicationInfo?.aiName || applicationName} />
            </div>
        );

    return (
        <Layout>
            <GlobalHeader />
            <div id="main-body">
                <Header style={{ backgroundColor: "var(--semi-color-bg-1)", borderTop: "1px solid var(--semi-color-border)" }}>
                    <Nav mode="horizontal" selectedKeys={state.selectedMenuKeys} onSelect={onSelectedMenu}>
                        <Nav.Header
                            logo={
                                <Avatar
                                    icon={appIcon}
                                    size={36}
                                    shape="square"
                                    style={{ backgroundColor: applicationInfo?.atBgco || "#efefef", marginRight: 10 }}
                                />
                            }
                            text={applicationInfo?.aiName || applicationName}
                        ></Nav.Header>

                        <MenuOutlined style={{ marginRight: 10 }} />

                        {Object.keys(routers).map((key) => {
                            const item = routers[key];
                            if (item.position === "global" && item.type === "menu")
                                if (item.subMenus && item?.isShowSub) {
                                    return (
                                        <Nav.Sub key={key} itemKey={key} text={item.title} icon={item.icon || null}>
                                            {Object.keys(item.subMenus).map((key1) => (
                                                <Nav.Item key={[key, key1].join("/")} itemKey={[key, key1].join("/")} text={item.subMenus[key1].title} />
                                            ))}
                                        </Nav.Sub>
                                    );
                                } else {
                                    return <Nav.Item key={key} itemKey={key} text={item.title} icon={item.icon || null} />;
                                }
                        })}

                        <Nav.Footer>
                            <Space size={10}>
                                <span>审核: {remoteOrganizationInfo?.isOpenExamine ? <Tag color="#87d068">开启</Tag> : <Tag color="#999">关闭</Tag>}</span>
                                <span>审批: {remoteOrganizationInfo?.isOpenApprove ? <Tag color="#87d068">开启</Tag> : <Tag color="#999">关闭</Tag>}</span>
                                <span>
                                    授权: {isStop ? <Tag color="#999">暂停</Tag> : isExpire ? <Tag color="#999">已过期</Tag> : <Tag color="#87d068">正常</Tag>}
                                </span>
                                {/* <span>角色: </span> */}
                            </Space>
                        </Nav.Footer>
                    </Nav>
                </Header>

                <Content
                    id="content-body"
                    style={{ backgroundColor: "var(--semi-color-fill-0)", position: "fixed", left: 0, top: 90, right: 0, bottom: 0, overflow: "hidden" }}
                >
                    <Outlet />
                    <FloatButton.BackTop visibilityHeight={200} target={() => document.getElementById("content-body")} />
                </Content>
            </div>
        </Layout>
    );
};

export default MainLayout;
